﻿using System;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using ZLWeb.WebApiConfigration;
using ZLWeb.WebApiRepository;
using ZLWeb.WebApiRepository.InterFace;
using ZLWeb.WebApiUtility;

namespace ZLWeb.WebApiInfrastructure.Filter
{
    public class SessionValidateAtrribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
        
            //以下注释为验证参数加入QueryString中的验证取值方法
            //var qs = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
            //string ClientVersion = qs["ClientVersion"];

            //由自定义http头获取验证信息-----begin noto by yanzhengyu----//
            var headers = actionContext.Request.Headers;

            var ClientName =
                headers.Contains("ClientName")
                    ? headers.FirstOrDefault(x => x.Key == "ClientName").Value.FirstOrDefault()
                    : string.Empty;
            var ClientVersion =
                headers.Contains("ClientVersion")
                    ? headers.FirstOrDefault(x => x.Key == "ClientVersion").Value.FirstOrDefault()
                    : string.Empty;
            var RandomCode =
                headers.Contains("RandomCode")
                    ? headers.FirstOrDefault(x => x.Key == "RandomCode").Value.FirstOrDefault()
                    : string.Empty;
            var pw = ClientName + "@" + ClientVersion + "@" + RandomCode;

            var pwd =
                headers.Contains("pwd")
                    ? headers.FirstOrDefault(x => x.Key == "pwd").Value.FirstOrDefault()
                    : string.Empty;
            //由自定义http头获取验证信息-----end noto by yanzhengyu----//
            //if (string.IsNullOrEmpty(ClientName) || string.IsNullOrEmpty(ClientVersion) ||
            //    string.IsNullOrEmpty(RandomCode) || string.IsNullOrEmpty(pwd))
            //{
            //    throw new ValidateException("Url验证失败！");
            //    return;
            //}
            //if (!pwd.Equals(DigestHelper.MD5Converter(pw)))
            //{
            //    throw new ValidateException("Url验证失败！");
            //    return;
            //}

            //ICheckRepository CheckRepository = new CheckRepository();
            //var su = CheckRepository.ClientNameCheck(ClientName);
            //if (!su)
            //{
            //    throw new ValidateException("客户端名验证失败！");
            //    return;
            //}
            //todo 服务端配置文件
            //try
            //{
            //    CheckRepository.VersionCheck(PipeWebServiceConfig.KvName, PipeWebServiceConfig.KvVer,
            //        Assembly.GetExecutingAssembly().GetName().Version.ToString(), ClientName, ClientVersion);
            //}
            //catch (System.Exception ex)
            //{
            //    throw new ValidateException("版本验证失败！");
            //}
        }
    }
}